package com.yuanxiao.common.web.xss;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * XSS过滤处理
 *
 * 使用HttpServletRequestWrapper重写Request请求参数
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private static final transient Logger log = LoggerFactory.getLogger(XssHttpServletRequestWrapper.class);

    //没被包装过的HttpServletRequest（特殊场景，需要自己过滤）
    HttpServletRequest orgRequest;
    //html过滤
    private final static HTMLFilter htmlFilter = new HTMLFilter();

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        orgRequest = request;
    }

    //通过ServletInputStream读取http请求传入的数据
    @Override
    public ServletInputStream getInputStream() throws IOException {
        //非json类型，直接返回
        if(!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))){
            return super.getInputStream();
        }

        //为空，直接返回
        String json = IOUtils.toString(super.getInputStream(), "utf-8");
        if (StringUtils.isBlank(json)) {
            return super.getInputStream();
        }

        //xss过滤
        json = xssEncode(json);
        final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return true;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bis.read();
            }
        };
    }

    @Override
    public String getParameter(String name) {
        String value = super.getParameter(xssEncode(name));
        if (StringUtils.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] parameters = super.getParameterValues(name);
        if (parameters == null || parameters.length == 0) {
            return null;
        }

        for (int i = 0; i < parameters.length; i++) {
            parameters[i] = xssEncode(parameters[i]);
        }
        return parameters;
    }

    @Override
    public Map<String,String[]> getParameterMap() {
        Map<String,String[]> map = new LinkedHashMap<>();
        Map<String,String[]> parameters = super.getParameterMap();
        for (String key : parameters.keySet()) {
            String[] values = parameters.get(key);
            for (int i = 0; i < values.length; i++) {
                values[i] = xssEncode(values[i]);
            }
            map.put(key, values);
        }
        return map;
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(xssEncode(name));
        if (StringUtils.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }

    private String xssEncode(String input) {
        return htmlFilter.filter(input);
    }

    /**
     * 获取最原始的request
     */
    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }

    /**
     * 获取最原始的request
     */
    public static HttpServletRequest getOrgRequest(HttpServletRequest request) {
        if (request instanceof XssHttpServletRequestWrapper) {
            return ((XssHttpServletRequestWrapper) request).getOrgRequest();
        }

        return request;
    }

    /**
     * 将容易引起注入的关键字的替换，防止sql注入
     * @param value 过滤前的值
     * @return 过滤后的值
     */
    private static String sqlValidate(String value) {

        log.info ("-------------> 执行 sqlValidate", value);

        log.info (value);

        if (value == null || value.isEmpty()) {
            return value;
        }
        // 防SQL注入转义
        value = StringEscapeUtils.escapeSql(value);

        // HTML防注入，个人建议使用第三种
        // 1.防HTML注入转义(HtmlUtils工具类，汉字不转义，双引号转义，存在JSON封装需要反转义)
        // value = HtmlUtils.htmlEscape(value);
        // 2.防HTML注入转义(StringEscapeUtils工具类，汉字也转义，取出时需要反转义)
        // value = StringEscapeUtils.escapeHtml(value);
        // 3.字符串替换法（通过各种循环替换字符串测试，最终还是replace替换效果最佳）
        // 3-1 将非法字符串 替换为 ""
        value = value.toLowerCase();//统一转为小写
        String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +
                "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|" +
                "table|from|grant|use|group_concat|column_name|" +
                "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +
                "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#";//过滤掉的sql关键字，可以手动添加
        String[] badStrs = badStr.split("\\|");
        for (int i = 0; i < badStrs.length; i++) {
            if (value.indexOf(badStrs[i]) >= 0) {
                value = value.replaceAll(badStrs[i], "");
            }
        }
        // 3-2 将非法字符串 的半角字符直接替换成全角字符
        /*value = value.replaceAll("<", "＜");
        value = value.replaceAll(">", "＞");
        value = value.replaceAll("'", "＇");
        value = value.replaceAll(";", "﹔");
        value = value.replaceAll("&", "＆");
        value = value.replaceAll("%", "﹪");
        value = value.replaceAll("#", "＃");
        value = value.replaceAll("select", "seleᴄt");// "c"→"ᴄ"
        value = value.replaceAll("truncate", "trunᴄate");// "c"→"ᴄ"
        value = value.replaceAll("exec", "exeᴄ");// "c"→"ᴄ"
        value = value.replaceAll("join", "jᴏin");// "o"→"ᴏ"
        value = value.replaceAll("union", "uniᴏn");// "o"→"ᴏ"
        value = value.replaceAll("drop", "drᴏp");// "o"→"ᴏ"
        value = value.replaceAll("count", "cᴏunt");// "o"→"ᴏ"
        value = value.replaceAll("insert", "ins℮rt");// "e"→"℮"
        value = value.replaceAll("update", "updat℮");// "e"→"℮"
        value = value.replaceAll("delete", "delet℮");// "e"→"℮"
        value = value.replaceAll("script", "sᴄript");// "c"→"ᴄ"
        value = value.replaceAll("cookie", "cᴏᴏkie");// "o"→"ᴏ"
        value = value.replaceAll("iframe", "ifram℮");// "e"→"℮"
        value = value.replaceAll("onmouseover", "onmouseov℮r");// "e"→"℮"
        value = value.replaceAll("onmousemove", "onmousemov℮");// "e"→"℮"*/
        return value;
    }

}
